//
//  TNewTask.m
//  iTimeline
//
//  Created by Mobioneer HV 02 on 1/14/13.
//  Copyright (c) 2013 Mobioneer Co., Ltd. All rights reserved.
//

#import "TNewTask.h"
#import "TTaskName.h"
#import "AppDelegate.h"
#import "TaskData.h"
#import "TSoundTask.h"
@interface TNewTask ()
{
    int _prioriry;
    NSDate *_time;
    NSString *_taskName;
    NSString *_sound;
    NSDateFormatter *_dateFormatter;
    UITextField *_textField;
    NSMutableArray *_week;
    BOOL aSwitch;
    BOOL _check;
    TaskData *data;
}
@end

@implementation TNewTask
@synthesize table = _table;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)config
{
    _check = 1;
    aSwitch = NO;
    _dateFormatter = [[NSDateFormatter alloc] init];
    [_dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [_dateFormatter setDateStyle:NSDateFormatterShortStyle];
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"vi_VN"];
    [_dateFormatter setLocale:usLocale];
    _time = [NSDate date];
    _prioriry = 1;
    _sound = @"Default";
    _taskName = @"Task";
    _week = [[NSMutableArray alloc]initWithObjects:@"0",@"0",@"0",@"0",@"0",@"0",@"0", nil];
}
-(void)returnSound:(NSString *)name
{
    _sound = name;
}
-(void)setPriority:(int)pri
{
    _prioriry = pri;
    
}
-(void)returnTaskName:(NSString *)name
{
    _taskName = name;
    [self.table reloadData];
}
-(void)repeat:(BOOL)done
{
    if(done)
    {
       // _week = week;
        aSwitch = done;
    }
    else
        aSwitch = NO;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(Done:)];
    self.navigationItem.rightBarButtonItem = addButton;
    self.navigationItem.title = @"New Task";
    [self config];
    // Do any additional setup after loading the view from its nib.
}
-(IBAction)Done:(id)sender
{
    if(_check)
    {
         
        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
        NSFetchRequest *request = [[NSFetchRequest alloc]init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"TaskData" inManagedObjectContext:delegate.managedObjectContext];
        [request setEntity:entity];
        data = [NSEntityDescription insertNewObjectForEntityForName:@"TaskData" inManagedObjectContext:delegate.managedObjectContext];
        data.taskName = _taskName;
        data.priority = [[NSNumber alloc]initWithInt:_prioriry];
        data.time = _time;
        data.complete = 0;
        data.sound = _sound;
        if(aSwitch)
        {
            NSString *temp = @"";
            for (NSString *str in _week)
                temp = [temp stringByAppendingString:str];
            data.repeat = temp;
            NSLog(@"%@",temp);
        }
        else data.repeat = @"0000000";
        NSError *error;
        if(![delegate.managedObjectContext save:&error])
        {
            NSLog(@"Save Fail!");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Warring" message:@"Save Fail!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        else
        {
            
            NSLog(@"Save Successed!");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Notify" message:@"Save Successed!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
            _check = NO;
        }
    }
    else if(!_check)
    {
        AppDelegate *delegate = [[UIApplication sharedApplication]delegate];
        data.taskName = _taskName;
        data.priority = [[NSNumber alloc]initWithInt:_prioriry];
        data.time = _time;
        data.complete = 0;
        data.sound = _sound;
        if(aSwitch)
        {
            NSString *temp = @"";
            for (NSString *str in _week)
                temp = [temp stringByAppendingString:str];
            data.repeat = temp;
            NSLog(@"%@",temp);
        }
        else data.repeat = @"0000000";
        NSError *error;
        if(![delegate.managedObjectContext save:&error])
        {
            NSLog(@"Save Fail!");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Warring" message:@"Save Fail!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
        else
        {
            NSLog(@"Save Successed!");
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Notify" message:@"Save Successed!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int indexer  = indexPath.row;
    if(indexer!=2)
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        }
        if(indexer==0)
        {
            cell.textLabel.text = @"Task name";
            cell.detailTextLabel.text = _taskName;
        }
        else if(indexer==1)
        {
            cell.textLabel.text = @"Time";
            cell.detailTextLabel.text = [_dateFormatter stringFromDate:_time];
        }
        else if(indexer == 3)
        {
            cell.textLabel.text = @"Repeat";
            if(aSwitch)
            {
                NSString *temp=@"";
                for (int i=0; i<7; i++)
                {
                    NSString *str = [_week objectAtIndex:i];
                    if([str intValue] == 1)
                    {
                        switch (i) {
                            case 0:
                                temp = [temp stringByAppendingString:@"Mon  "];
                                break;
                            case 1:
                                temp = [temp stringByAppendingString:@"Tue  "];
                                break;
                            case 2:
                                temp = [temp stringByAppendingString:@"Wed  "];
                                break;
                            case 3:
                                temp = [temp stringByAppendingString:@"Thu  "];
                                break;
                            case 4:
                                temp = [temp stringByAppendingString:@"Fri  "];
                                break;
                            case 5:
                                temp = [temp stringByAppendingString:@"Sat  "];
                                break;
                            case 6:
                                temp = [temp stringByAppendingString:@"Sun  "];
                                break;
                            default:
                                break;
                        }
                    }
                }
                cell.detailTextLabel.text = temp;
            }
            else
                cell.detailTextLabel.text = @"Never";
            cell.accessoryType = UITableViewCellStyleValue1;
        }
        else if(indexer == 4)
        {
            cell.textLabel.text = @"Sound";
            cell.detailTextLabel.text = _sound;
            cell.accessoryType = UITableViewCellStyleValue1;
        }
       
        return cell;
    }
    else
    {
        static NSString *CellIdentifier = @"TNewTaskCell";
        TNewTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil][0];
            cell.delegate = self;
        }
       
        return cell;
    }
    return nil;
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 }
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
//        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Task Name" message:@"this gets covered" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
//        _textField= [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
//        _textField.backgroundColor = [UIColor greenColor];
//        _textField.borderStyle = UITextBorderStyleRoundedRect;
//        [_textField becomeFirstResponder];
//        [myAlertView addSubview:_textField];
//        [myAlertView show];
        TTaskName *taskName = [[TTaskName alloc]initWithNibName:@"TTaskName" bundle:nil];
        taskName.tn = _taskName;
        taskName.delegate = self;
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil]; [[self navigationItem] setBackBarButtonItem:backButton];
        [self.navigationController pushViewController:taskName animated:YES];
    }
    else if (indexPath.row == 1)
    {
        DatePicker *datePicker = [[DatePicker alloc] init];
        datePicker.delegate = self;
        [datePicker show];
    }
    else if(indexPath.row == 3)
    {
        TRepeat *repeat =[[TRepeat alloc]initWithNibName:@"TRepeat" bundle:nil];
        repeat.aSwit = aSwitch;
        repeat.week = _week;
        repeat.delegate = self;
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil]; [[self navigationItem] setBackBarButtonItem:backButton];
        [self.navigationController pushViewController:repeat animated:YES];
        
       // [self.navi pushViewController:repeat animated:YES];
        
    }
    else if(indexPath.row == 4)
    {
        TSoundTask *listSound = [[TSoundTask alloc]initWithNibName:@"TSoundTask" bundle:nil];
        listSound.delegate = self;
        listSound.name = _sound;
        UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil]; [[self navigationItem] setBackBarButtonItem:backButton];
        [self.navigationController pushViewController:listSound animated:YES];
    }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
    {
        _taskName = _textField.text;
        [self.table reloadData];
    }
}
-(void)datePicker:(DatePicker *)datePicker dismissWithDone:(BOOL)done
{
    _time = datePicker.picker.date;
    [self.table reloadData];
}
- (void)viewDidUnload {
    [self setTable:nil];
    [super viewDidUnload];
}
-(void)viewWillAppear:(BOOL)animated
{
    [self.table reloadData];
}
@end
